package com.game.othello;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class OthelloPanel extends JPanel {
    private static final int BOARD_SIZE = 8; // 棋盘大小
    private static final int CELL_SIZE = 50; // 每个单元格的大小
    private static final Color BOARD_COLOR = new Color(0, 100, 0); // 棋盘颜色
    private static final Color LINE_COLOR = Color.BLACK; // 线条颜色
    private static final Color BLACK_STONE_COLOR = Color.BLACK; // 黑棋颜色
    private static final Color WHITE_STONE_COLOR = Color.WHITE; // 白棋颜色

    private final OthelloBoard gameBoard;
    private boolean isBlackTurn;

    public OthelloPanel() {
        this.gameBoard = new OthelloBoard(BOARD_SIZE);
        this.isBlackTurn = true;

        setPreferredSize(new Dimension(BOARD_SIZE * CELL_SIZE, BOARD_SIZE * CELL_SIZE));
        setBackground(BOARD_COLOR);
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int x = e.getX() / CELL_SIZE;
                int y = e.getY() / CELL_SIZE;
                if (gameBoard.isValidMove(x, y, isBlackTurn ? OthelloBoard.BLACK : OthelloBoard.WHITE)) {
                    gameBoard.placeStone(x, y, isBlackTurn ? OthelloBoard.BLACK : OthelloBoard.WHITE);
                    isBlackTurn = !isBlackTurn;
                    repaint();
                }
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        drawBoard(g);
        drawStones(g);
    }

    private void drawBoard(Graphics g) {
        g.setColor(LINE_COLOR);
        for (int i = 0; i < BOARD_SIZE; i++) {
            int x1 = i * CELL_SIZE;
            int y1 = 0;
            int x2 = i * CELL_SIZE;
            int y2 = BOARD_SIZE * CELL_SIZE;
            g.drawLine(x1, y1, x2, y2);

            x1 = 0;
            y1 = i * CELL_SIZE;
            x2 = BOARD_SIZE * CELL_SIZE;
            y2 = i * CELL_SIZE;
            g.drawLine(x1, y1, x2, y2);
        }
    }

    private void drawStones(Graphics g) {
        for (int y = 0; y < BOARD_SIZE; y++) {
            for (int x = 0; x < BOARD_SIZE; x++) {
                int centerX = x * CELL_SIZE + CELL_SIZE / 2;
                int centerY = y * CELL_SIZE + CELL_SIZE / 2;
                if (gameBoard.getStone(x, y) == OthelloBoard.BLACK) {
                    g.setColor(BLACK_STONE_COLOR);
                    g.fillOval(centerX - 15, centerY - 15, 30, 30);
                } else if (gameBoard.getStone(x, y) == OthelloBoard.WHITE) {
                    g.setColor(WHITE_STONE_COLOR);
                    g.fillOval(centerX - 15, centerY - 15, 30, 30);
                }
            }
        }
    }
}